<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
		<title>index</title>
		<script src="kissy-min.js"></script>
		<style type="text/css">
			img {
				margin: 10px;
			}
		</style>
	</head>
	<body>
		<div id="contain">

		</div>
		<script>
			var DOM = KISSY.DOM, Event = KISSY.Event,Anim=KISSY.Anim;
			var newData = {};
			var contain;
			var nextUrl;
			function group(photos) {
				if (photos) {
					for (var i = 0; i < photos.length; i++) {
						var timeStr = showTime(photos[i].time);
						if (newData[timeStr]) {
							newData[timeStr].push(photos[i]);
						} else {
							newData[timeStr] = [];
							newData[timeStr].push(photos[i]);
						}
					}
				}
				//alert(JSON.stringify(newData));
			}
			function showTime(time) {
				var myTime = new Date(time);
				var day = myTime.getDate();
				var month = myTime.getMonth() + 1;
				var year = myTime.getFullYear();
				day = day < 10 ? '0' + day : day;
				month = month < 10 ? '0' + month : month;
				return year + '-' + month + '-' + day;
			}
						
			function getJsonData(nextPageUrl) {
				if(!nextPageUrl){
					nextPageUrl='http://photo-sync.herokuapp.com/photos';
				}
				console.log(nextPageUrl);
				contain = document.getElementById('contain');
				KISSY.io.jsonp(nextPageUrl, function(data) {
					
					var myData = data;
					nextUrl=myData.nextURL;					
					group(myData.photos);
					//console.log(newData);
					for (var timeString in newData) {
						var h3 = document.createElement('h3');
						h3.innerHTML = timeString;

						var num = newData[timeString].length;
						var ul = document.createElement('ul');
						for (var i = 0; i < num; i++) {
							var img = document.createElement('img');
							var nowImg = newData[timeString][i];
							if (nowImg.width > 160 && nowImg.width > nowImg.height) {
								img.width = 160;
							} else if (nowImg.height > 160) {
								img.height = 160;
							}
							img.src = nowImg.imageURL;
							if(i%5 == 0 && i != 0){
								var brtag=document.createElement('br');
								ul.appendChild(brtag);
							}
							ul.appendChild(img);							
						}
						contain.appendChild(h3);
						contain.appendChild(ul);
					}
				});

			}
			
			window.onscroll = function() {
				var allH = DOM.docHeight();
				var viewH = DOM.viewportHeight();
				var scrollH = DOM.scrollTop(window);
				if (viewH + scrollH >= allH - 100) {										
					getJsonData(nextUrl);
				}
			}
			window.onload = function() {
				getJsonData();
			}
		</script>
		
	</body>
</html>
